package com.luoyuanxiangvip.admin.core.jwt;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 自定义token
 * </p>
 *
 * @author luoyuanxiang <p>luoyuanxiangvip.com</p>
 * @since 2019/5/26 18:53
 */
@Component
public class JwtToken {

    @Resource
    private JwtProperties jwtProperties;

    /**
     * 获取用户名从token中
     * @param token token
     * @return 主题或用户名
     */
    public String getUsernameFromToken(String token) {
        try {
            return getClaimFromToken(token).getSubject();
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 获取jwt发布时间
     * @param token token
     * @return 时间
     */
    public Date getIssuedAtDateFromToken(String token) {
        try {
            return getClaimFromToken(token).getIssuedAt();
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 获取jwt失效时间
     * @param token token
     * @return 时间
     */
    public Date getExpirationDateFromToken(String token){
        try {
            return getClaimFromToken(token).getExpiration();
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 获取jwt接收者
     * @param token token
     * @return string
     */
    public String getAudienceFromToken(String token){
        try {
            return getClaimFromToken(token).getAudience();
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 获取私有的jwt claim
     * @param token token
     * @param key key
     * @return String
     */
    private String getPrivateClaimFromToken(String token, String key){
        try {
            return getClaimFromToken(token).get(key).toString();
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 获取md5 key从token中
     * @param token token
     * @return string
     */
    public String getMd5KeyFromToken(String token){
        return getPrivateClaimFromToken(token, jwtProperties.getMd5Key());
    }

    /**
     * 获取jwt的payload部分
     * @param token token
     * @return Claims
     */
    private Claims getClaimFromToken(String token) {
        return Jwts.parser()
                .setSigningKey(jwtProperties.getSecret())
                .parseClaimsJws(token)
                .getBody();
    }

    /**
     * 解析token是否正确,不正确会报异常
     * @param token token
     */
    public boolean parseToken(String token){
        Claims body = null;
        try {
            body = getClaimFromToken(token);
        } catch (Exception e) {
            return true;
        }
        return body.size() <= 0;
    }

    /**
     * 验证token是否失效
     * true:过期   false:没过期
     * @param token token
     * @return Boolean
     */
    public Boolean isTokenExpired(String token){
        final Date expiration = getExpirationDateFromToken(token);
        return expiration.before(new Date());
    }

    /**
     * 生成token(通过用户名和签名时候用的随机数)
     * @param userName 用户名
     * @param randomKey 用户密码或key
     * @return token
     */
    public String generateToken(String userName, String randomKey) {
        Map<String, Object> claims = new HashMap<>(1);
        claims.put(jwtProperties.getMd5Key(), randomKey);
        return doGenerateToken(claims, userName);
    }

    /**
     * token 刷新
     * @param token token
     * @return new token
     */
    public String refreshToken(String token) {
        final Date createdDate = new Date();
        final Date expirationDate = new Date(System.currentTimeMillis() + jwtProperties.getExpiration() * 1000);
        String subject = this.getUsernameFromToken(token);
        Claims claims = this.getClaimFromToken(token);
        return Jwts.builder()
                .setClaims(claims)
                .setSubject(subject)
                .setIssuedAt(createdDate)
                .setExpiration(expirationDate)
                .signWith(SignatureAlgorithm.HS512, jwtProperties.getSecret())
                .compact();
    }

    /**
     * 生成token
     * @param claims 需要加密的用户信息
     * @param subject 主题
     * @return token
     */
    private String doGenerateToken(Map<String, Object> claims, String subject) {
        final Date createdDate = new Date();
        final Date expirationDate = new Date(System.currentTimeMillis() + jwtProperties.getExpiration() * 1000);
        return Jwts.builder()
                .setClaims(claims)
                .setSubject(subject)
                .setIssuedAt(createdDate)
                .setExpiration(expirationDate)
                .signWith(SignatureAlgorithm.HS512, jwtProperties.getSecret())
                .compact();
    }
}
